<!--
* description: 总部月计划制定
* author: wangml
* createdDate: 2020-12-01

-->

<template>
  <div class="app-container app-container-table">
    <!-- 单表格模版页面 -->
    <one-table-template
      ref="multipleTable"
      :supplement="supplement"
      :position-span="positionSpan"
      :dynamic-api-config="dynamicApiConfig"
      :dynamic-buttons="dynamicButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="dynamicTableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-page-size="10"
      :dynamic-api-style="apiStyle"
      :refresh-table-key="refreshTableKey"
      :showbtn-length="4"
      :callback-obj="callbackObj"
      :page-size-array="newpagesizeArr"
      :value-object="valObj"
      @hiddenColData="hiddenColData"
    />
    <p style="position:absolute;right:110px;bottom:-3px;color:red">当前总计划数量：{{ totalnum }}台</p>
    <sales-creation
      ref="carType"
      :popups-visible.sync="curPopupsVisible"
      :dialog-status="dialogStatus"
      :dynamic-edit-row-data="rowData"
      :popups-state="popstate"
    />
    <real-time-statistics
      ref="realtimeStatic"
      :popups-visible.sync="diashow"
    />

  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/planReport'
import salesCreation from './salesCreation1'
import realTimeStatistics from './realTimeStatistics'
import commData from '../common/index.js'
import { exportExcel } from '@/utils/getTimeString'

export default {
  name: 'HeadquarterSalesPlan',
  components: {
    OneTableTemplate,
    salesCreation,
    realTimeStatistics
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      newpagesizeArr: ['10', '50', '100', '500', '1000', '2000'],
      supplement: {
        supplements: '请在导入前确认模板字段格式是否正确,配置填编码,年份：20xx，月份：1~12，周度：1~52',
        IsSupplement: true,
        span: 8
      },
      totalnum: 0,
      positionSpan: [8, 8],
      rowData: {},
      diashow: false,
      dialogStatus: 'headquarters',
      curPopupsVisible: false,
      genCodeFiled: null,
      selectList: {},
      selectData: [],
      clickRowsData: {},
      popstate: 'add',
      showdia: false,
      // 指定请求类型 可以统一在 utils/config.js中配置
      apiStyle: 'restful',
      dynamicApiConfig: api.makeSalesPlan,
      refreshTableKey: '0',
      ruleSettingShow: false,
      // table表格查询API配置对象
      // 动态组件-查询条件
      tableComponents:
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
            ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents
            : [
              ...commData.ModelOptions(2),
              {
                compKey: 'comKey6',
                labelName: '制定月份：',
                codeField: 'makingMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                format: 'yyyy-MM',
                // dateOptionsType: '3',
                isMust: false,
                span: 6
              },
              {
                compKey: 'planMonthComp',
                labelName: '计划月份：',
                codeField: 'planMonth',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'month',
                format: 'yyyy-MM',
                // dateOptionsType: '3',
                startTime: '',
                // disabled: true,
                // parentFileds: 'disabled:makingMonth-planMonth--false',
                type: 'inputText',
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey7',
                labelName: '提报类型：',
                codeField: 'careHost',
                component: () => import('@/components/org/commonSelect'),
                type: 'dropdownList',
                oFields: 'careHost,careHost1',
                options: [
                  { careHost: '总部', careHost1: '总部' },
                  { careHost: '门店', careHost1: '门店' }
                ],
                isMul: false,
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey9',
                labelName: '制作人：',
                codeField: 'creator',
                component: () => import('@/components/org/commonInput'),
                type: 'inputText',
                isMust: false,
                span: 6
              },
              // {
              //   compKey: 'comKey10',
              //   labelName: '提报来源：',
              //   codeField: 'planSource',
              //   component: () => import('@/components/org/commonInput'),
              //   type: 'inputText',
              //   isMust: false,
              //   span: 6
              // },
              {
                compKey: 'comKey11',
                labelName: '优先级别：',
                codeField: 'priorityLevel',
                lookuptype: 'VE1227',
                component: () => import('@/components/org/commonSelect'),
                type: 'inputText',
                isMul: true,
                isMust: false,
                span: 6
              },
              {
                compKey: 'comKey12',
                labelName: '计划状态：',
                codeField: 'planStatus',
                // lookuptype: 'VE1112',
                component: () => import('@/components/org/commonSelect'),
                customObj: { listQuery: { lookupTypeCode: 'VE1112', attribute1: '1' }},
                type: 'dropdownList',
                isMul: true,
                isMust: false,
                span: 6
              },
              {
                compKey: 'compKey13',
                labelName: '制作时间：',
                codeField: 'startTime,endTime',
                component: () => import('@/components/org/datePicker/datePicker.vue'),
                dateType: 'daterange',
                isMul: true,
                isMust: false
              }
            ],
      formField: {
        careHost: '',
        planMonth: '',
        creator: '',
        planSource: '',
        priorityLevel: '',
        makingMonth: '',
        planStatus: '',
        startTime: '',
        endTime: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: ''
      },
      // 动态组件-按钮
      dynamicButtons: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableButtons
        : [
          {
            compKey: 'comKey11',
            type: 'text',
            size: 'small',
            text: '导入模板下载',
            name: '',
            position: 'right',
            clickEvent: () =>
              this.export(
                api.templateDownload.APIUrl,
                '总部月计划模板.xlsx',
                { dataType: 'excel' }
              )
          },
          {
            compKey: 'comKey0',
            type: 'primary',
            size: 'small',
            name: 'search',
            position: 'right',
            clickEvent: () => this.queryTable(1),
            text: '查询'
          },
          {
            compKey: 'comKey1',
            type: '',
            size: '',
            name: 'reset',
            position: 'right',
            clickEvent: () => this.reset(),
            text: '重置'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: 'newOrder',
            position: 'left',
            clickEvent: () => this.add(),
            text: '制定'
          },
          {
            compKey: 'comKey2',
            type: '',
            size: 'small',
            name: 'importTemplate',
            position: 'upload',
            // clickEvent: () => this.importtemp(),
            text: '导入'
          },
          {
            compKey: 'comKey5',
            type: '',
            size: 'small',
            name: 'saveSubmit',
            position: 'left',
            clickEvent: () => this.sendreport(),
            text: '月计划发送',
            disabled: true
          },
          {
            compKey: 'comKey4',
            type: '',
            size: 'small',
            name: '',
            position: 'left',
            clickEvent: () => this.statistic(),
            text: '实时统计'
          },
          {
            compKey: 'comKey3',
            type: '',
            size: 'small',
            name: '',
            position: 'left',
            disabled: true,
            clickEvent: () => this.delete(),
            text: '删除'
          },
          {
            compKey: 'comKey6',
            type: '',
            size: 'small',
            name: 'export',
            position: 'left',
            clickEvent: () => {
              exportExcel(this.formField,
                api.headquartersExport.APIUrl,
                'exportStoreMonthSalePlan', '总部月计划制定')
            },
            text: '导出'
          }
        ],
      // 动态组件-表格网格列
      dynamicTableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols
        : [
          {
            prop: 'releaseId',
            label: '主键ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发控制ID',
            hidden: true,
            alwaysHidden: true
          },
          {
            label: '操作',
            minWidth: 180,
            fixed: true,
            isComponent: true,
            comps: [
              {
                compKey: 'propKey1',
                labelName: '编辑',
                codeField: 'editPlan',
                component: () => import('@/components/org/linkButton'),
                // component: () => import('@/components/org/datePicker/datePicker.vue'),
                rowFileds: 'show:planStatusCode-SCOP已驳回|待发送',
                clickEvent: (index) => this.edit(index)
              }
            ]
          },
          {
            prop: 'planStatusCode',
            label: '计划状态',
            rowFileds: 'disabled:planStatusCode-未提交|待发送'
          },
          {
            prop: 'makingMonth',
            label: '制定月份'
          },
          {
            prop: 'ttCode',
            label: '22位码',
            width: 175
          },
          {
            prop: 'planMonth',
            label: '计划月份',
            width: 120
          },
          {
            prop: 'planWeek',
            label: '计划周度'
          },
          {
            prop: 'planNum',
            label: '计划数量'
          },
          {
            prop: 'careHost',
            label: '提报类型'
          },
          {
            prop: 'carSeriesCode',
            label: '车系编码'
          },
          {
            prop: 'carSeriesCn',
            label: '车系名称'
          },
          {
            prop: 'carConfigCode',
            label: '基础车型编码'
          },
          {
            prop: 'carConfigCn',
            label: '基础车型名称',
            width: 110
          },
          {
            prop: 'optionalPagCode',
            label: '选装包编码'
          },
          {
            prop: 'optionalPagName',
            label: '选装包名称'
          },
          {
            prop: 'carColorCode',
            label: '车身颜色编码'
          },
          {
            prop: 'carColorName',
            label: '车身颜色名称'
          },
          {
            prop: 'carIncolorCode',
            label: '内饰颜色编码'
          },
          {
            prop: 'carIncolorName',
            label: '内饰颜色名称'
          },
          {
            prop: 'creator',
            label: '制作人'
          },
          {
            prop: 'createdDate',
            label: '制作时间'
          },
          {
            prop: 'sendTime',
            label: '月计划发送时间'
          },
          {
            prop: 'priorityLevel',
            label: '优先级别'
          }
          // {
          //   prop: 'planSource',
          //   label: '提报来源'
          // }
        ],
      valObj: {
        a: 1
      },
      // 单表格模版页面组件回调事件
      callbackObj: {
        // 查询后回调
        onQueryReturn: () => {
          this.$requestAPI({
            apiUrl: api.queryHqMonthSum.APIUrl,
            variables: { ...this.formField }
          }).then(res => {
            console.log(res.rows[0].planNums)
            this.totalnum = res.rows[0].planNums
          }).catch(err => {
            console.log(err)
          })
        },
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectList.updateControlId = selection.map((item) => {
            return item.updateControlId
          })
          this.selectList.monthPlanId = selection.map((item) => {
            return item.monthPlanId
          })
          this.selectList.planStatus = selection.map((item) => {
            return item.planStatus
          })
          this.selectionList = selection
          this.list = this.selectionList.reduce((pre, cur) => {
            pre.push({ monthPlanId: cur.monthPlanId,
              updateControlId: cur.updateControlId,
              planStatus: cur.planStatus,
              planMonth: cur.planMonth,
              planWeek: cur.planWeek,
              carSerId: cur.carSerId,
              carConfigId: cur.carConfigId,
              carOptionalpagId: cur.carOptionalpagId,
              carColorId: cur.carColorId,
              carIncolorId: cur.carIncolorId,
              ttCode: cur.ttCode,
              planNum: cur.planNum
            })
            return pre
          }, [])
          this.handleSelectionChange(selection)
        }

      }
    }
  },
  watch: {
    'formField.makingMonth': {
      handler(val) {
        if (!val) {
          this.formField.planMonth = ''
        } else {
          // 有值 动态设置时间禁用
          this.tableComponents.filter(item => item.compKey === 'planMonthComp')[0].startTime = val
        }
      }
    },
    'formField': {
      handler(form) {
        if (form.makingMonth !== '') {
          if (new Date(form.planMonth) <= new Date(form.makingMonth)) {
            this.$message('计划月份大于制定月份，请重新选择!')
            this.formField.planMonth = ''
            const comp = this.$refs['multipleTable'].$refs['planMonthComp'][0]
            comp.modelCode = ''
            comp.$children[0].$children[0].$children[0].focus()
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    // 列表查询
    this.queryTable(1)
    // let fileName = this.$route.matched[this.$route.matched.length - 1].meta.title.replace('/', '')
    // console.log(fileName)
  },
  methods: {
    handle() { },
    add() {
      this.dialogStatus = 'headquarters'
      this.popstate = 'add'
      this.curPopupsVisible = true
    },
    // 月计划发送
    sendreport() {
      this.$confirm('确定要发送吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const that = this
        this.$requestAPI({
          apiUrl: api.hqSendPlan.APIUrl,
          variables: {
            updateControlIds: this.selectList.updateControlId,
            monthPlanIds: this.selectList.monthPlanId,
            infoList: that.selectionList
          }
        }).then(res => {
          if (res.result === '1') {
            this.$message('计划发送成功!')
            this.$refs['multipleTable'].queryTable(1)
          } else {
            this.$message(res.msg)
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },
    statistic() {
      this.diashow = true
    },
    // 导出
    export(url, filename, variable) {
      this.$requestAPI({
        apiUrl: url,
        variables: variable,
        filename: filename
      }).then(res => {
        this.$utils.downloadFile(res, filename)
      }).catch(err => {
        console.log(err)
      })
    },
    // 自动生成codeField
    genUtil: (array) => (attr) => array.reduce((p, c) => { p[c[attr]] = ''; return p }, {}),
    // 保存 或新增 后会调用此方法
    popClose(type) {
      this.showdia = false
      if (type === 1) {
        this.queryTable(1)
      }
    },
    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.dynamicButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        if (isCheck) {
          const del = selection.every((item) => {
            return (item.planStatus === '8' || item.planStatus === '1')
          })
          if (del) {
            btns[0].disabled = !del
            btns[1].disabled = !del
          } else {
            btns[0].disabled = true
            btns[1].disabled = true
          }
        } else {
          btns[0].disabled = true
          btns[1].disabled = true
        }
        // btns.forEach((item) => {
        //   item.disabled = !isCheck
        // })
      }
    },
    hiddenColData(data) {
      if (data && data.length > 0) {
        this.refreshTableKey += 1
        this.dynamicTableCols = data
      }
    },
    edit(idx) {
      // const time = this.$utils.dateFormatChange('2020-12-23', '{y}-{m}')
      this.rowData = this.$refs.multipleTable.list[idx]
      this.dialogStatus = 'hqEdit'
      this.popstate = 'edit'
      this.curPopupsVisible = true
    },
    // 删除
    delete(selectData) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$requestAPI({
          apiUrl: api.confirmWeekPlanDelete.APIUrl,
          variables: { updateControlId: this.selectList.updateControlId, monthPlanId: this.selectList.monthPlanId, planStatus: this.selectList.planStatus }
        }).then(res => {
          if (res.result === '1') {
            this.$message(res.msg ? res.msg : '删除成功')
            this.queryTable(1)
          }
        })
      }).catch(() => {})
    },
    // 新增
    // add() {
    //   this.clickRowsData = {}
    //   this.popstate = 'add'
    //   this.showdia = true
    // },
    // selectRowsData(rowdata) {
    // },
    // 文件上传前
    handleChange(params) {
      // const url = api.headquartersImport.APIUrl
      // this.$requestImport(url, params, (response) => {
      //   this.uploadSuccess(response)
      // }, '?token=' + this.$store.getters.token)
    },
    // 上传返回结果处理
    uploadSuccess(response) {
      if (response.result === '1' && response.msg !== '') {
        this.$confirm('<p style="height:350px;overflow:auto">' + response.msg + '</p>', '导入结果', {
          dangerouslyUseHTMLString: true,
          showCancelButton: false,
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          this.$refs['multipleTable'].queryTable(1)
        })
      } else if (response.result === '0') {
        this.$message({ type: 'warning', message: response.msg })
        // this.$refs.searchBtns.$refs.upload[0].clearFiles()
      } else {
        this.$alert(`文件导入失败${response.msg}`, '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
    },
    // 文件改变
    handFileListChange(params) {
      this.attachHandleChange(params)
    },
    // 上传
    attachHandleChange(param) {
      const loading = this.$loading({
        text: '正在导入'
      })
      const that = this
      const url = api.headquartersImport.APIUrl
      that
        .$requestUpload(url, param)
        .then((response) => {
          loading.close()
          this.uploadSuccess(response)
        })
        .catch((err) => {
          loading.close()
          that.modeCode = ''
          console.info(err)
        })
    },

    // 文件格式过滤
    beforeAvatarUpload(file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      if (!extension && !extension2) {
        this.$alert('上传文件只能为Excel文件', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        })
      }
      return extension || extension2
    },
    beforeRemove(file, fileList) {
      // console.log(file, fileList)
    },
    handleExceed(file, fileList) {

    },
    // getSelectable(data) {
    //   if (data.planStatus === '待发送' ||
    //     data.planStatus === '未提交') {
    //     return true
    //   }
    //   return false
    // },
    // 查看附件
    checkFile(index, type) {
      // location.href = process.env.VUE_APP_BASE_API + this.$refs['multipleTable'].list[index].downloadUrl
      window.open(this.$refs['multipleTable'].list[index][type])
    }

  }
}
</script>

<style lang="scss" scoped>
  /deep/button.el-button.icon-importTemplate  {
    margin: 0 10px;
    line-height: 20px;
  }
  /deep/.el-button.el-button--small.iconfont.icon-newOrder{
    line-height: 20px;
  }
  /deep/.el-button.el-button--small{
    line-height: 20px;
  }
</style>

